package nvd

import (
	"time"
	"cve-db/models"
	"cve-db/config"
	log "github.com/sirupsen/logrus"
	"fmt"
	"cve-db/db"
)

func Fetchernvd(driver db.DB, year int) error {
	thisyear := time.Now().Year()
	years := []int{}
	for i:=year; i<thisyear+1; i++{
		years = append(years, i)
	}

	defer driver.CloseDB()

	metas, err := FetchLatestFeedMeta(driver, years)
	if err != nil {
		log.Errorf("%s", err)
		return err
	}

	if len(metas) == 0 {
		log.Errorf("No meta files fetched")
		return err
	}

	needUpdates := []models.FeedMeta{}
	for _, m := range metas {
		if m.Newly() {
			needUpdates = append(needUpdates, m)
			log.Infof("     Newly: %s", m.URL)
		} else if m.OutDated() {
			needUpdates = append(needUpdates, m)
			log.Infof("  Outdated: %s", m.URL)
		} else {
			log.Infof("Up to date: %s", m.URL)
		}
	}

	if len(needUpdates) == 0 {
		log.Infof("Already up to date")
		return fmt.Errorf("Not need upate")
	}

	cves := []models.CveDetail{}

	cves, err = FetchConvert(needUpdates)

	if err != nil {
		log.Errorf("%s", err)
		return err
	}

	log.Infof("Fetched %d CVEs", len(cves))
	log.Infof("Inserting NVD into DB (%s).", driver.Name())

	if err := driver.InsertNvdJSON(cves); err != nil {
		log.Errorf("Failed to insert. dbpath: %s, err: %s",
			config.Conf.DBDsn, err)
		return err
	}

	if err := UpdateMeta(driver, needUpdates); err != nil {
		log.Fatalf("Failed to Update meta. dbpath: %s, err: %s", config.Conf.DBDsn, err)
		return err
	}
	return err
}
